import './index.css';

import React, {
  useEffect,
  useState,
} from 'react';

import {
  message,
  Modal,
} from 'antd';
import { useMoralis } from 'react-moralis';

import { CloseCircleFilled } from '@ant-design/icons';

const Connect = () => {
  const [open, setOpen] = useState(false);
  const [account, setAccount] = useState();

  const { authenticate, isAuthenticated, Moralis, logout, user } = useMoralis();

  const showModal = () => {
    if (account != null) {
      message.warning({
        content: "you are already logged in",
        duration: 2,
        style: { marginTop: "20vh" },
      });
    } else {
      setOpen(true);
    }
  };

  const handleOk = (e) => {
    console.log(e);
    setOpen(false);
  };

  const handleCancel = (e) => {
    console.log(e);
    setOpen(false);
  };

  //连接metamask
  const ConnectMetaMask = async () => {
    console.log(isAuthenticated);
    if (!isAuthenticated) {
      await authenticate({
        signingMessage: "Welcome to NodeFrom!",
        duration: 2,
        style: { marginTop: "20vh" },
      })
        .then((user) => {
          setAccount(user.get("ethAddress"));
          setOpen(false);
          message.success({
            content: "login successful",
            duration: 2,
            style: { marginTop: "20vh" },
          });
        })
        .catch((err) => {
          message.warning({
            content: "login cancel",
            style: {
              marginTop: "20vh",
            },
          });
          console.log(err);
        });
    } else {
      message.success({
        content: "you are logged in",
        duration: 2,
        style: { marginTop: "20vh" },
      });
    }
  };

  //连接ConnectWallet
  const ConnectWallet = async () => {
    if (!isAuthenticated) {
      await authenticate({ provider: "walletconnect" })
        .then(function (user) {
          console.log(user.get("ethAddress"));
        })
        .catch(function (error) {
          console.log(error);
        });
    }
  };

  //断开连接
  const Disconnect = async () => {
    await logout();
    setAccount(null);
    message.success({
      content: "logged out",
      duration: 2,
      style: { marginTop: "20vh" },
    });
  };

  // 初始化用户
  useEffect(() => {
    if (isAuthenticated) {
      setAccount(user.get("ethAddress"));
    }
  }, [isAuthenticated]);

  return (
    <>
      <button className="connect" onClick={showModal}>
        {account == null
          ? "Connect Wallet"
          : account.slice(0, 4) + "..." + account.slice(-4)}
      </button>

      {isAuthenticated && (
        <button className="logout" onClick={Disconnect}>
          Disconnect
        </button>
      )}

      <Modal
        title="Connect Wallet"
        open={open}
        onOk={handleOk}
        onCancel={handleCancel}
        footer={null}
        mask={false}
        closeIcon={<CloseCircleFilled twoToneColor="pink" />}
        okButtonProps={{
          disabled: true,
        }}
        cancelButtonProps={{
          disabled: true,
        }}
      >
        <div className="connect-group">
          <div className="cn-btn" onClick={() => ConnectMetaMask()}>
            <img src={[require("../../assets/icon/Group 70.png")]} />
            <p>MetaMask</p>
          </div>
          <div className="cn-btn" onClick={() => ConnectWallet()}>
            <img src={[require("../../assets/icon/image 3.png")]} />
            <p>WalletConnect</p>
          </div>
        </div>
      </Modal>
    </>
  );
};

export default Connect;
